import Vuex from 'vuex'
import Vue from 'vue'
import { getUserInfo, getSimpleUserInfo } from '../src/API/userInfo'
Vue.use(Vuex)
// 初始的 state 对象
var initState = {
  // token 的信息对象
  tokenInfo: {},
  userInfo: {},
  userSimpleInfo: {}
}
const stateStr = localStorage.getItem('state')

if (stateStr) {
  // 加载本地的数据

  initState = JSON.parse(stateStr)
}

export default new Vuex.Store({
  state: initState,
  mutations: {

    savaLocalStore (state) {
      localStorage.setItem('state', JSON.stringify(state))
    },
    upTokenInfo (state, el) {
      state.tokenInfo = el
      // 如果希望在 Mutation A 中调用 Mutation B，需要通过 this.commit() 方法来实现
      // this 表示当前的 new 出来的 store 实例对象
      this.commit('savaLocalStore')
    },
    updataUserInfo (state, payload) {
      state.userInfo = payload
      // console.log(payload)
      this.commit('savaLocalStore')
    },
    updateUserProfile (state, payload) {
      state.userSimpleInfo = payload
      this.commit('savaLocalStore')
    },
    clearToken (state) {
      state.tokenInfo = {}
      state.userInfo = {}
      state.userProfile = {}
      // 2. 将清空后的 state 存储到本地
      this.commit('savaLocalStore')
    }
  },
  actions: {
    async initUserInfo (state) {
      const { data: res } = await getUserInfo()
      if (res.message === 'OK') {
        this.commit('updataUserInfo', res.data)
      }
    },
    async initSimpleUserInfo (state) {
      const { data: res } = await getSimpleUserInfo()

      if (res.message === 'OK') {
        this.commit('updateUserProfile', res.data)
      }
    }
  }
})
